import React, {PureComponent} from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Table, Modal, Card, Icon, Divider} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';
import {hasPermissions} from './utils';
import {conventSorter} from '../utils';
import styles from './style.css';
import PartSelectPanel from './PartSelectPanel';
import TextInput from 'Shared/components/TextInput';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import WrappedTag from '../common/WrappedTag';
import {getList, updateDetail} from './api';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
import {unionWith, pullAllBy} from 'lodash';
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
class EditPanel extends PureComponent {
    state = {
        partCode: '',
        partName: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        sortField: 'partCode',
        isDesc: false,
        currentCondition: {},
        showPart: false,
        deleteKeys: [],
        addKeys: [],
        showHistory: false,
    };
    componentDidMount() {
        this.onClickSearchBtn();
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    };
    handleFilterPressEnter = (value, name) => {
        this.setState({
            [name]: value
        }, this.onClickSearchBtn);
    };

    showPart = () => {
        this.setState({
            showPart: !this.state.showPart
        });
    };
    showHistory = () => {
        this.setState({
            showHistory: !this.state.showHistory
        });
    };
    getColumnSearchProps = dataIndex => ({
        filterDropdown: () => (
            <div>
                <TextInput
                    name={dataIndex}
                    onBlur={this.onChange}
                    value={this.state[dataIndex]}
                    onPressEnter={this.handleFilterPressEnter}
                    className={styles.filterInput}/>
                <Button
                    type="primary"
                    onClick={this.onClickSearchBtn}
                    icon="search"
                    size="small"
                    className={styles.filterQueryBtn}>
                    {this.props.intl.formatMessage({
                        id: 'editPanel.filterBtn.query',
                        defaultMessage: '查询'
                    })}
                </Button>
                <Button
                    data-name={dataIndex}
                    onClick={this.onClearFilter}
                    size="small"
                    className={styles.filterResetBtn}>
                    {this.props.intl.formatMessage({
                        id: 'editPanel.filterBtn.reset',
                        defaultMessage: '重置'
                    })}
                </Button>
            </div>
        ),
        filterIcon: () => <Icon type="filter" theme="filled" className={this.state[dataIndex] ? styles.iconColor : ''} />,
    })
    onQuery = condition => {
        this.setState({
            isFetching: true
        });
        getList(this.props.id, condition).then(res => {
            if(res.ok)
                this.setState({
                    isFetching: false,
                    message: '',
                    data: res.data,
                    currentCondition: condition
                });
            else
                this.setState({
                    isFetching: false,
                    data: {},
                    message: res.message
                });
        });
    };
    onClickSearchBtn = () => {
        const condition = {
            partCode: this.state.partCode,
            partName: this.state.partName,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    };
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    };
    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    };
    onChange = (value, name) => {
        this.setState({
            [name]: value
        });
    };

    onClickDeletePart = id => {
        this.setState({
            isFetching: true
        });
        updateDetail(this.props.id, {
            deleteNoSubmitPartIds: [id],
            addNoSubmitPartIds: EMPTY_ARRAY
        }).then(res => {
            if(res.ok) {
                const {content = EMPTY_ARRAY} = this.state.data;
                const {partId, partCode, partName} = content.find(item => item.partId === id) || EMPTY_OBJECT;
                const record = {
                    id: partId,
                    code: partCode,
                    name: partName
                };
                const addKeys = pullAllBy([...this.state.addKeys], [record], 'id');
                const deleteKeys = unionWith(pullAllBy([record], [...this.state.addKeys, ...this.state.deleteKeys], 'id'), [...this.state.deleteKeys]);
                this.setState({
                    deleteKeys,
                    addKeys,
                });
                this.onClickSearchBtn();
            }
            this.setState({
                isFetching: false
            });
        });
    }

    onSelectPart = record => {
        const details = record.map(item => item.id);
        return updateDetail(this.props.id, {
            deleteNoSubmitPartIds: EMPTY_ARRAY,
            addNoSubmitPartIds: details
        }).then(res => {
            if(res.ok) {
                const deleteKeys = pullAllBy([...this.state.deleteKeys], [...record], 'id');
                const addKeys = unionWith(pullAllBy([...record], [...this.state.deleteKeys, ...this.state.addKeys], 'id'), [...this.state.addKeys]);
                this.setState({
                    showPart: false,
                    hasOperat: true,
                    deleteKeys,
                    addKeys,
                });
                this.onClickSearchBtn();
            }
            return res.ok;
        });
    };

    onClearFilter = e => {
        const {name} = e.target.dataset;
        this.setState({
            [name]: '',
            pageIndex: PAGE.index,
        }, this.onClickSearchBtn);
    }
    render() {
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const operations = [];
        if(this.state.deleteKeys.length || this.state.addKeys.length)
            operations.push(<Button className={styles.btnMargin} key="history" onClick={this.showHistory} size="small">
                {this.props.intl.formatMessage({
                    id: 'editPanel.btn.history',
                    defaultMessage: '本次操作记录'
                })}
            </Button>);

        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'editPanel.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
                sorter: true,
                ...this.getColumnSearchProps('partCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'editPanel.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
                ...this.getColumnSearchProps('partName')
            }
        ];
        if(this.props.isEditable) {
            operations.push(<Button key="add" onClick={this.showPart} size="small">
                {this.props.intl.formatMessage({
                    id: 'editPanel.btn.add',
                    defaultMessage: '新增'
                })}
            </Button>);
            columns.push({
                title: this.props.intl.formatMessage({
                    id: 'editPanel.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => (
                    <WrappedPopconfirm
                        id={record.partId}
                        title={this.props.intl.formatMessage({
                            id: 'editPanel.popconfirm.message',
                            defaultMessage: '删除后将更新清单，是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'editPanel.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'editPanel.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onClickDeletePart}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'editPanel.delete',
                                defaultMessage: '删除'
                            })}
                        </a>
                    </WrappedPopconfirm>

                )
            });
        }
        
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        return (
            <Card title={this.props.intl.formatMessage({
                id: 'editPanel.card.title',
                defaultMessage: '不可提报备件清单'
            })}
            extra={operations}>
                <Table
                    className={`white-space-nowrap ${styles.tableCursor}`}
                    rowKey="partId"
                    dataSource={data.content || EMPTY_ARRAY}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />

                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'editPanel.partModal.title',
                        defaultMessage: '备件信息查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPart}
                    onCancel={this.showPart}>
                    <PartSelectPanel saleOrderTypeId={this.props.id} onSelect={this.onSelectPart} />
                </Modal>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'editPanel.addTags.title',
                        defaultMessage: '本次操作记录'
                    })}
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showHistory}
                    width="80%"
                    onCancel={this.showHistory}>
                    <DescriptionList col={1} size="large" className="editPanel">
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'editPanel.parts.add',
                                defaultMessage: '已新增'
                            })}>
                            {this.state.addKeys.map(r => (
                                <WrappedTag className={styles.modalTag} key={r.id} id={r.id}>
                                    {`(${r.code})${r.name}`}
                                </WrappedTag>
                            ))}
                        </Description>
                    </DescriptionList>
                    <Divider />
                    <DescriptionList col={1} size="large" className="editPanel">
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'editPanel.parts.delete',
                                defaultMessage: '已删除'
                            })}>
                            {this.state.deleteKeys.map(r => (
                                <WrappedTag className={styles.modalTag} key={r.id} id={r.id}>
                                    {`(${r.code})${r.name}`}
                                </WrappedTag>
                            ))}
                        </Description>
                    </DescriptionList>
                </Modal>
            </Card>
        );
    }
}

EditPanel.propTypes = {
    isEditable: PropTypes.bool.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};


import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getData = selectorFactory(['page', 'domainData', 'initData', 'saleOrderTypes']);
const getEditable = createSelector(
    state => getPermissions(state),
    state => getData(state),
    (state, ownProps) => ownProps.id,
    (permissions, types, id) => {
        const {options = EMPTY_ARRAY} = types.find(item => item.id === id) || EMPTY_OBJECT;
        return hasPermissions(permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update);
    }
);
const mapStateToProps = (state, ownProps) => ({
    isEditable: getEditable(state, ownProps),
});
export default connect(
    mapStateToProps,
    null
)(injectIntl(EditPanel));

